package com.feihong.txgw.ui.activity.product;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.adapter.base.BaseQuickAdapter;
import com.bumptech.glide.Glide;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.product.ProductListAdapter;
import com.feihong.txgw.inter.contract.product.IProListContract;
import com.feihong.txgw.json.goodsCart.TerminalListParser;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.shopcar.bean.TerminalEntiyt;
import com.feihong.txgw.tx_precenter.ProListMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;

import java.util.List;

import butterknife.BindView;

import static com.feihong.txgw.ui.fragment.home.DiscoverFragment.INTENT_PRODUCTID;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW. (购物车界面暂无调用)
 * 飞宏电子
 * 终端列表页面
 */

public class ProductListActivity extends BaseMVPCompateActivity<IProListContract.AbProListMainPrecenter> implements View.OnClickListener,
        IProListContract.IProListMainView, BaseQuickAdapter.RequestLoadMoreListener {

    private ProductListAdapter mProductLisetAdapter;
    String store_id = "";
    @BindView(R.id.lay_loading)
    RelativeLayout mLoadingLayout;
    @BindView(R.id.terminal_no_layout)
    LinearLayout mTerminalNullLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mReQueryData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refresh)
    SwipeRefreshLayout mSwipeRefreshLayout;

    /**
     * 数据是否满一页
     */
    private boolean isFullPage = false;
    /**
     * 当前列表是否有数据
     */
    private boolean isHasData = false;
    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_productlist;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setPageTitle("精选优品");
        setBackButtonFinish();
        Intent store = getIntent();
        store_id = store.getStringExtra("store_id");
        mSwipeRefreshLayout.setColorSchemeColors(Color.rgb(223, 47, 47));
        mLoadingLayout.setVisibility(View.GONE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isHasData = false;
                mPresenter.getTerminalFirstGoods(store_id);
            }
        });
        initAdapter();
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        mProductLisetAdapter = new ProductListAdapter(R.layout.product_list_item);
        mProductLisetAdapter.setOnLoadMoreListener(this, recyclerView);
        mProductLisetAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.add_shopcar_icon:
                        TerminalEntiyt terminalEntiyt = (TerminalEntiyt) adapter.getItem(position);
                        if (terminalEntiyt != null) {
                            mPresenter.addGoodsToShopCar(terminalEntiyt);
                        } else {
                            showSystemToast("添加失败，请重新添加");
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        mProductLisetAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TerminalEntiyt terminalEntiyt = (TerminalEntiyt) adapter.getItem(position);
                Intent intent = new Intent();
                intent.setClass(ProductListActivity.this, ProductInfoActivity.class);
                intent.putExtra(INTENT_PRODUCTID, terminalEntiyt.getSku_id());
                intent.putExtra(ProductInfoActivity.INTENT_NAME, terminalEntiyt.getSku_name());
                startActivity(intent);
            }
        });
        recyclerView.setAdapter(mProductLisetAdapter);
    }

    @Override
    public void bindData() {
        mReQueryData.setOnClickListener(this);
        getData();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    /**
     * 获取数据
     */
    private void getData() {
        mPresenter.getTerminalGoods(store_id);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Glide.get(this).clearMemory();
        System.gc();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.re_query_data_layout:
                mConnectErrorLayout.setVisibility(View.GONE);
                mLoadingLayout.setVisibility(View.VISIBLE);
                getData();
                break;
            default:
                break;
        }
    }

    /**
     * 列表数据
     *
     * @param goodsEntities
     * @param isLoadEnd     数据加载完毕
     */
    @Override
    public void getTerminalGoodsResult(TerminalListParser goodsEntities, boolean isLoadEnd) {

        isFullPage = isLoadEnd;
        List<TerminalEntiyt> mGoods;
        mGoods = goodsEntities.getData().getList();
        finishRefreshing();
        if(!isHasData){
            mConnectErrorLayout.setVisibility(View.GONE);
            mTerminalNullLayout.setVisibility(View.GONE);
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
            mProductLisetAdapter.setNewData(mGoods);
            isHasData = true;
        }else {
          mProductLisetAdapter.addData(mGoods);
        }
        mProductLisetAdapter.loadMoreComplete();
    }


    @Override
    public void addGoodsToShopCarError() {
        showSystemToast("加入购物车失败！请检查网络");
    }

    @Override
    public void loadEnd() {
        finishRefreshing();
        if (!isHasData) {
            mConnectErrorLayout.setVisibility(View.GONE);
            mTerminalNullLayout.setVisibility(View.VISIBLE);
            mSwipeRefreshLayout.setVisibility(View.GONE);
            mProductLisetAdapter.loadMoreEnd();
        }else {
            mProductLisetAdapter.loadMoreEnd(!isFullPage);
        }
    }

    @Override
    public void loadDataComplated() {
        finishRefreshing();
    }

    @Override
    public void loadDataError() {
        finishRefreshing();
        mProductLisetAdapter.loadMoreFail();
        if (isHasData) {
            mConnectErrorLayout.setVisibility(View.GONE);
            mSwipeRefreshLayout.setVisibility(View.VISIBLE);
        } else {
            mConnectErrorLayout.setVisibility(View.VISIBLE);
            mSwipeRefreshLayout.setVisibility(View.GONE);
        }
        showSystemToast(getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return ProListMainPrecenter.create();
    }

    private void finishRefreshing(){
        if(mSwipeRefreshLayout.isRefreshing()){
            mSwipeRefreshLayout.setRefreshing(false);
        }

        if(mLoadingLayout.getVisibility() == View.VISIBLE){
            mLoadingLayout.setVisibility(View.GONE);
        }
    }
    /**
     * 列表加载更多监听
     */
    @Override
    public void onLoadMoreRequested() {
        getData();
    }
}
